/**
	The Minerva Project, DAG Scheduling Tools
	Copyright (C) 2006 Florin Pop & Stefan Bucur

	This program is free software; you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
 */
package ro.pub.cs.minerva.scheduler;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import ro.pub.cs.minerva.resource.Resource;

/**
 * @author Stefan Bucur
 *
 */
public class TaskScheduleResult {

	private HashMap<Resource, List<TaskMapping>> results;
	private List<Resource> resources;
	
	void addResource(Resource resource) {
		List<TaskMapping> mappingList = new LinkedList<TaskMapping>();
		
		results.put(resource, mappingList);
		
		resources.add(resource);
	}
	
	void removeResource(Resource resource) {
		resources.remove(resource);
		
		results.remove(resource);
	}
	
	boolean containsResource(Resource resource) {
		return resources.contains(resource);
	}
	
	void addMapping(TaskMapping mapping) {
		Resource resource = mapping.getResource();
		
		if (!results.containsKey(resource))
			addResource(resource);
		
		List<TaskMapping> mappingList = results.get(resource);
		
		mappingList.add(mapping);
	}
	
	void sortMappings() {
		for (List<TaskMapping> crMapList : results.values()) {
			Collections.sort(crMapList, new Comparator<TaskMapping>() {

				public int compare(TaskMapping o1, TaskMapping o2) {
					if (o1.getStartTime() == o2.getStartTime())
						return 0;
					
					return (o1.getStartTime() < o2.getStartTime()) ?
							-1 : 1;
				}
				
			});
		}
	}
	
	public TaskScheduleResult() {
		results = new HashMap<Resource, List<TaskMapping>>();
		resources = new ArrayList<Resource>();
	}
	
	public Resource[] getResources() {
		return resources.toArray(new Resource[0]);
	}
	
	public int getResourceCount() {
		return resources.size();
	}
	
	public Resource getResource(int index) {
		return resources.get(index);
	}
	
	public TaskMapping[] getMappings(Resource resource) {
		if (resource != null) {
			List<TaskMapping> mappings = results.get(resource);
			
			return mappings.toArray(new TaskMapping[0]);
		} else {
			return null;
		}
	}
	
	public int getMappingCount(Resource resource) {
		if (resource != null) {
			List<TaskMapping> mappingList = results.get(resource);
			
			if (mappingList != null)
				return mappingList.size();
			else
				return -1;
		} else {
			return -1;
		}
	}
}
